var backgroundInfo = {
    version: "1.0.0",
    setIntervalId: 0, //循环标识
    allCardList: {
        biliCardList: [],
        weiboCardList: []
    },
    settings: {
        refreshFrequency: 10000, //10秒
        biliChecked: true,
        weiboChecked: false
    },

    //设置循环
    SetInterval(refreshFrequency) {
        this.setIntervalId = setInterval(function() {
            backgroundInfo.getAllDynamic();
        }, refreshFrequency);
    },

    //获取动态，总入口
    getAllDynamic() {
        //bili
        if (backgroundInfo.settings.biliChecked == true) {
            getBiliDynamic.getDynamic();
        } else {
            backgroundInfo.allCardList.biliCardList = [];
        }

        //weibo
        if (this.settings.weiboChecked == true) {
            getWeiboDynamic.getDynamic();
        } else {
            this.allCardList.weiboCardList = [];
        }
    },

    SendNotice(title, message, imageUrl, time) {
        if (imageUrl) {
            chrome.notifications.create(time + '_', {
                iconUrl: '../image/icon.png',
                message: message,
                title: title,
                imageUrl: imageUrl,
                type: "image"
            });
        } else {
            chrome.notifications.create(time + '_', {
                iconUrl: '../image/icon.png',
                message: message,
                title: title,
                type: "basic"
            });
        }
    },

    //Chrome通知
    notice(title, msg, img, timeStamp) {
        if (img) {
            chrome.notifications.create(timeStamp + '_', {
                iconUrl: "../img/logo/IconBig.png",
                message: msg,
                title: title,
                imageUrl: img,
                type: "image"
            });
        } else {
            chrome.notifications.create(timeStamp + '_', {
                iconUrl: "../img/logo/IconBig.png",
                message: msg,
                title: title,
                type: "basic"
            });
        }
    },

    //初始化
    Init() {
        let that = this;
        chrome.storage.local.get(['settings'], result => {
            if (result.settings == undefined) {
                chrome.storage.local.set({
                    settings: that.settings,
                });
            } else {
                that.settings = result.settings;
            }
            that.getAllDynamic();
            that.SetInterval(that.settings.refreshFrequency);
        });

        // 添加通知点击事件
        chrome.notifications.onClicked.addListener(id => {
            let { biliCardList = [], weiboCardList = [] } = backgroundInfo.allCardList;
            let cardList = [...weiboCardList, ...biliCardList];
            let todynamic = cardList.filter(x => x.timeStamp + "_" == id);
            if (todynamic != null && todynamic.length > 0) {
                chrome.tabs.create({ url: todynamic[0].url });
            } else {
                console.log("最近列表内没有找到该标签");
            }
        });
    },

    Get(url, success) {
        try {
            let xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
                    success(xhr.responseText);
                }
            }
            xhr.send();
        } catch (error) {
            console.log(error);
        }
    },
}

let getBiliDynamic = {
    //XSG
    // url: "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?visitor_uid=0&host_uid=5345634&offset_dynamic_id=0&need_top=1&platform=web",
    url: "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?visitor_uid=5345634&host_uid=401742377&offset_dynamic_id=0&need_top=1&platform=web",
    target: "https://space.bilibili.com/401742377/dynamic",
    cardList: [],
    getDynamic() {
        // this的定义之后会改变，用that固定一下当前this
        let that = this;
        that.cardList = [];
        //在url后调用随机数参数，使请求不会从缓存中调用
        url = that.url + "&random=" + Math.random().toFixed(3);

        $.ajax({
            url: that.url + "&random=" + Math.random().toFixed(3),
            type: "GET",
            contentType: "application/json;charset=UTF-8",
            // async: false,
            success: function(data) {
                if (data.code == 0 && data.data != null && data.data.cards != null && data.data.cards.length > 0) {
                    let cards = data.data.cards;
                    // desc.type   1转发 2动态 4无图动态 8视频 64专栏
                    cards.map(function(x) {
                        let card = JSON.parse(x.card);
                        // console.log(x);
                        // console.log(card);
                        // console.log("-----------------------------------------------------\n");
                        let biliCard = {
                            source: "bili", //来源
                            timeStamp: x.desc.timestamp, //时间戳
                            type: x.desc.type,
                            url: "https://t.bilibili.com/" + x.desc.dynamic_id_str
                        }

                        //2动态
                        if (x.desc.type == 2) {
                            biliCard.content = card.item.description;

                            if (card.item.pictures != null && card.item.pictures.length > 0) {
                                biliCard.image = (card.item.pictures && card.item.pictures.length > 0) ? card.item.pictures[0].img_src : null;
                            }
                        }

                        //4无图动态
                        if (x.desc.type == 4) {
                            biliCard.content = card.item.content;
                        }

                        //8视频
                        if (x.desc.type == 8) {
                            biliCard.content = card.dynamic;

                            biliCard.image = card.pic;
                        }

                        //64专栏
                        if (x.desc.type == 64) {
                            biliCard.image = (card.image_urls && card.image_urls.length > 0) ? card.image_urls[0] : null;
                            biliCard.content = card.summary;
                        }

                        if (x.desc.type == 2 || x.desc.type == 4 || x.desc.type == 8 || x.desc.type == 64) {
                            that.cardList.push(biliCard);
                        }

                    });

                    //按时间戳排序
                    // console.log(that.cardList);
                    that.cardList.sort(function(x, y) {
                        return y.timeStamp - x.timeStamp;
                    });

                    //将新列表放入allCardList之前，先与旧List比较，判断是否有更新
                    that.isNew(that.cardList);
                    backgroundInfo.allCardList.biliCardList = that.cardList;
                }
            },
            error: function() {
                console.log("获取bilibili接口数据失败。");
            }
        });
    },

    isNew(newCardList) {
        let oldCardList = backgroundInfo.allCardList.biliCardList;
        //如果有更新
        if (oldCardList && oldCardList.length > 0 && oldCardList[0].timeStamp != newCardList[0].timeStamp && newCardList[0].timeStamp > oldCardList[0].timeStamp) {
            let dynamicInfo = newCardList[0];
            //0为视频 1为动态
            if (dynamicInfo.type == 0) {
                backgroundInfo.notice("[哔哩哔哩]有新动态！", `${dynamicInfo.content.replace(/\n/g, "")}`, dynamicInfo.image, dynamicInfo.timeStamp)
            } else {
                if (!!!dynamicInfo.pictures) {
                    backgroundInfo.notice("[哔哩哔哩]有新动态！", `${dynamicInfo.content.replace(/\n/g, "")}`, dynamicInfo.image, dynamicInfo.timeStamp);
                } else {
                    backgroundInfo.notice("[哔哩哔哩]有新动态", `${dynamicInfo.content.replace(/\n/g, "")}`, null, dynamicInfo.timeStamp);
                }
            }
        }
    }
}

backgroundInfo.Init();